package com.view.subOperation;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.Vector;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.DefaultTreeSelectionModel;

import com.dto.CourseDTO;
import com.dto.ProblemItemDTO;
import com.dto.TeachDTO;
import com.dto.TeacherDTO;
import com.service.Course;
import com.service.ProblemItem;
import com.service.Teach;
import com.util.tool.NodeValue;
import com.util.tool.ProblemType;
import com.view.problemManage.AddProblem;
import com.view.problemManage.UpdateProblem;

@SuppressWarnings("serial")
public class TeacherSelectFrame extends JInternalFrame {
	private static TeacherSelectFrame selectFrame;
	private JSplitPane splitPane;
	private JTree courseTree;
	private JPanel showPane;
	private DefaultTreeModel treeModel;
	private JScrollPane scrollPane;
	private JTable libraryTable;
	private DefaultTableModel libraryModel;
	private JComboBox<String> cbb_type;
	private CourseDTO courseDTO;
	private TeacherDTO teacherDTO;
	private int clickCount = -1;

	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					TeacherSelectFrame frame = new TeacherSelectFrame();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public TeacherSelectFrame() {
		setBounds(100, 100, 1178, 639);
		setDefaultCloseOperation(JInternalFrame.EXIT_ON_CLOSE);
		splitPane = new JSplitPane();
		splitPane.setBounds(0, 0, 891, 468);
		getContentPane().add(splitPane);

		courseTree = new JTree();
		courseTree.setFont(new Font("华文楷体", Font.BOLD, 16));
		courseTree.addTreeSelectionListener(new TreeSelectionListener() {
			@Override
			public void valueChanged(TreeSelectionEvent e) {
				do_valueChanged_action(e);
			}
		});
		splitPane.setLeftComponent(courseTree);

		showPane = new JPanel();
		JToolBar toolBar = new JToolBar();
		toolBar.setBounds(0, 0, 985, 23);
		JButton btnLink = new JButton("关联课程");
		btnLink.setFont(new Font("华文楷体", Font.BOLD, 16));
		btnLink.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				do_link_action(e);
			}
		});

		JButton btnUpdate = new JButton("题库状态更新");
		btnUpdate.setFont(new Font("华文楷体", Font.BOLD, 16));
		btnUpdate.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				do_update_action(e);
			}
		});

		JButton btnAdd = new JButton("题库状态情况添加");
		btnAdd.setFont(new Font("华文楷体", Font.BOLD, 16));
		btnAdd.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				do_add_action(e);
			}
		});

		JButton btnDelete = new JButton("题库状态删除");
		btnDelete.setFont(new Font("华文楷体", Font.BOLD, 16));
		btnDelete.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				do_delete_action(e);
			}
		});

		JButton btnRefresh = new JButton("刷新");
		btnRefresh.setFont(new Font("华文楷体", Font.BOLD, 16));
		btnRefresh.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				do_refresh_action(e);
			}
		});

		String[] types = { "", "单选题", "多选题", "判断题", "问答题" };
		showPane.setLayout(null);

		toolBar.add(btnLink);
		toolBar.add(btnAdd);
		toolBar.add(btnUpdate);
		toolBar.add(btnDelete);
		toolBar.add(btnRefresh);
		showPane.add(toolBar);

		scrollPane = new JScrollPane();
		scrollPane.setBounds(0, 67, 985, 389);
		libraryTable = new JTable();
		libraryTable.setFont(new Font("华文宋体", Font.BOLD, 14));
		libraryModel = new DefaultTableModel();

		String[] headers = { "问题编号", "序号", "题目类型", "题目内容", "选项内容", "答案",
				"题表公共信息", "备注" };
		libraryModel.setColumnIdentifiers(headers);
		libraryTable.setModel(libraryModel);
		libraryTable.setRowHeight(30);
		libraryTable.setFont(new Font("华文楷体", Font.BOLD, 14));
		libraryTable.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				clickCount = libraryTable.getSelectedRow();
			}
		});
		setTableCellRenderer();

		scrollPane.setViewportView(libraryTable);
		showPane.add(scrollPane);
		splitPane.setRightComponent(showPane);

		JPanel selectPane = new JPanel();
		selectPane.setBounds(0, 23, 985, 44);
		showPane.add(selectPane);
		selectPane.setLayout(null);

		cbb_type = new JComboBox<String>();
		cbb_type.setFont(new Font("华文楷体", Font.BOLD, 16));
		cbb_type.setBounds(10, 5, 158, 26);
		selectPane.add(cbb_type);
		cbb_type.setModel(new DefaultComboBoxModel<String>(types));

		JButton btnFind = new JButton("题库状态查询");
		btnFind.setFont(new Font("华文楷体", Font.BOLD, 16));
		btnFind.setBounds(217, 5, 148, 26);
		selectPane.add(btnFind);
		btnFind.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				do_find_action(e);
			}
		});

		splitPane.setDividerSize(5);
		splitPane.setDividerLocation(130);
	}

	public void setTeacherDTO(TeacherDTO teacherDTO) {
		this.teacherDTO = teacherDTO;
		showTree();
	}

	public void setCourseDTO(CourseDTO courseDTO) {
		this.courseDTO = courseDTO;
	}

	private void setTableCellRenderer() {
		/* 设置表格数据居中显示 */
		DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
		renderer.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
		libraryTable.setDefaultRenderer(Object.class, renderer);

		/* 隐藏首属性列 */
		TableColumn tc = libraryTable.getColumnModel().getColumn(0);
		tc.setMinWidth(0);
		tc.setMaxWidth(0);
		tc.setPreferredWidth(0);
		tc.setResizable(false);
		/* 设置列宽 */
		TableColumn tc_num = libraryTable.getColumnModel().getColumn(1);
		tc_num.setPreferredWidth(1);
	}

	protected void do_find_action(ActionEvent e) {
		try {
			/* 先清空表中数据 */
			if (libraryModel.getRowCount() > 0) {
				libraryModel.setRowCount(0);
			}

			String problem_type = (String) cbb_type.getSelectedItem();
			String course_id = courseDTO.getC_id();

			List<ProblemItemDTO> problemItems = new ProblemItem()
					.getProblemItems(course_id,
							ProblemType.getIndex(problem_type));

			if (problemItems.size() > 0) {
				int k = 0;
				Vector<Object> v_result = null;
				for (int i = 0; i < problemItems.size(); i++) {
					ProblemItemDTO problemItem = problemItems.get(i);
					v_result = new Vector<Object>();
					v_result.add(problemItem.getP_id());
					v_result.add(new Integer(++k));
					v_result.add(ProblemType.getName(problemItem.getPt_id()));
					v_result.add(problemItem.getP_content());
					v_result.add(problemItem.getChooise_content());
					v_result.add(problemItem.getAnswer());
					v_result.add(problemItem.getP_common_info());
					v_result.add(problemItem.getRemark());
					libraryModel.addRow(v_result);
				}
			}
		} catch (Exception ex) {
			// 此处不做任何处理
		}
	}

	protected void do_refresh_action(ActionEvent e) {
		try {
			showTree();
			do_find_action(e);
		} catch (Exception ex) {
		}
	}

	protected void do_delete_action(ActionEvent e) {
		if (clickCount >= 0) {
			int result = JOptionPane.showConfirmDialog(null, "确定删除该项纪录?");
			if (result == JOptionPane.OK_OPTION) {

				boolean success = new ProblemItem()
						.delete((String) libraryModel.getValueAt(clickCount, 0));

				if (success) {
					JOptionPane.showMessageDialog(null, "删除成功!");
					libraryModel.removeRow(clickCount);

					for (int i = 0; i < libraryModel.getRowCount(); i++) {
						libraryModel.setValueAt(new Integer(i + 1), i, 1);
					}
				} else {
					JOptionPane.showMessageDialog(null, "删除失败!");
				}
			}
			clickCount = -1;
		} else {
			JOptionPane.showMessageDialog(null, "请先选择要删除的记录！");
		}
	}

	protected void do_add_action(ActionEvent e) {
		if (courseDTO != null) {
			AddProblem.display();
			AddProblem.getInstance().setCourseDTO(courseDTO);

		} else {
			JOptionPane.showMessageDialog(null, "请先选择相应课程!");
		}
	}

	protected void do_update_action(ActionEvent e) {
		if (clickCount >= 0) {
			Object[] params = new Object[7];
			params[0] = libraryModel.getValueAt(clickCount, 0);
			params[1] = libraryModel.getValueAt(clickCount, 2);
			params[2] = libraryModel.getValueAt(clickCount, 3);
			params[3] = libraryModel.getValueAt(clickCount, 4);
			params[4] = libraryModel.getValueAt(clickCount, 5);
			params[5] = libraryModel.getValueAt(clickCount,
					libraryModel.getColumnCount() - 1);
			params[6] = courseDTO.getC_id();

			ProblemItemDTO problemItemDTO = new ProblemItemDTO(params);

			UpdateProblem.display();
			UpdateProblem.getInstance().setDTO(problemItemDTO, courseDTO);
			if ("判断题".equals(params[1]) || "问答题".equals(params[1])) {
				UpdateProblem.getInstance().getTa_chooise_content()
						.setEnabled(false);
				UpdateProblem.getInstance().getTa_chooise_content()
						.setBackground(Color.LIGHT_GRAY);
			}
		} else {
			JOptionPane.showMessageDialog(null, "请先选择要修改的记录！");
		}
	}

	protected void do_link_action(ActionEvent e) {
		LinkCourse.display();
		LinkCourse.getInstance().setTeacherDTO(teacherDTO);
	}

	private void showTree() {
		Course course_service = new Course();
		CourseDTO course = course_service.getCourseById("001");
		DefaultMutableTreeNode root = new DefaultMutableTreeNode(new NodeValue(
				course.getC_name(), course));

		List<TeachDTO> teaches = new Teach().getTeachesById(teacherDTO
				.getT_id());

		for (int i = 0; i < teaches.size(); i++) {
			CourseDTO courseDTO = course_service.getCourseById(teaches.get(i)
					.getC_id());
			DefaultMutableTreeNode node = new DefaultMutableTreeNode(
					new NodeValue(courseDTO.getC_name(), courseDTO));
			root.add(node);
		}
		treeModel = new DefaultTreeModel(root);
		courseTree.setModel(treeModel);
		courseTree.getSelectionModel().setSelectionMode(
				DefaultTreeSelectionModel.SINGLE_TREE_SELECTION);
	}

	protected void do_valueChanged_action(TreeSelectionEvent e) {
		DefaultMutableTreeNode node = (DefaultMutableTreeNode) courseTree
				.getLastSelectedPathComponent();

		if (node == null) {
			return;
		}

		/* 获取课程信息 */
		courseDTO = (CourseDTO) ((NodeValue) node.getUserObject()).getObject();

		/* 根据新的节点值动态加载新的数据 */
		loadNewData();
	}

	private void loadNewData() {
		Vector<Object> v_result = null;
		List<ProblemItemDTO> problemItems = new ProblemItem()
				.getProblemItems(courseDTO.getC_id());

		/* 当选择不同节点后，先清空表格信息 */
		if (libraryModel.getRowCount() > 0) {
			libraryModel.setRowCount(0);
		}

		if (problemItems.size() > 0) {

			int k = 0;
			for (int i = 0; i < problemItems.size(); i++) {
				ProblemItemDTO problemItem = problemItems.get(i);
				v_result = new Vector<Object>();
				v_result.add(problemItem.getP_id());
				v_result.add(new Integer(++k));
				v_result.add(ProblemType.getName(problemItem.getPt_id()));
				v_result.add(problemItem.getP_content());
				v_result.add(problemItem.getChooise_content());
				v_result.add(problemItem.getAnswer());
				v_result.add(problemItem.getP_common_info());
				if (problemItem.getRemark() != null
						&& !"".equals(problemItem.getRemark())) {
					v_result.add(problemItem.getRemark());
				} else {
					v_result.add(courseDTO.getC_name());
				}
				libraryModel.addRow(v_result);
			}
		}
	}

	public static void display() {
		if (selectFrame == null) {
			selectFrame = new TeacherSelectFrame();
		}
		selectFrame.setVisible(true);
		selectFrame.setResizable(false);
	}

	public static TeacherSelectFrame getInstance() {
		if (selectFrame == null) {
			selectFrame = new TeacherSelectFrame();
		}
		return selectFrame;
	}
}
